package com.hz.ruoyilgorder.websocket;

import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

public class MyWebSocketHandler extends TextWebSocketHandler {
    // 存储所有的 WebSocket 连接
    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("新的 WebSocket 连接: " + session.getId());
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息：" + message.getPayload());
        session.sendMessage(new TextMessage("服务器收到：" + message.getPayload()));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("WebSocket 连接关闭: " + session.getId());
    }

    // 后端主动推送消息给所有 WebSocket 连接
    public static void sendMessageToAll(String message) {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));  // 发送 TextMessage 消息
                    System.out.println("消息已发送: " + message);  // 确保打印出发送的消息
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
               // System.out.println("WebSocket session 已关闭, 跳过发送");
            }
        }
    }

}
